
function searchAllElement() {
  const allElements = container.querySelectorAll('.draggable');
  const result = [];

  allElements.forEach(el => {
    const props = {};

    // 标准属性
    if (el.id) props.id = el.id;
    props.text = el.textContent;
    // 将 style 属性解析为对象
    if (el.hasAttribute('style')) {
      const styleObj = {};
      const styleString = el.getAttribute('style');
      styleString.split(';').forEach(rule => {
        const [key, value] = rule.split(':').map(s => s && s.trim());
        if (key && value) styleObj[key] = value;
      });
      props.style = styleObj;
    }

    // data-* 属性
    for (const key in el.dataset) {
      props[`data-${key}`] = el.dataset[key];
    }

    // 只保留有属性的元素
    if (Object.keys(props).length > 0) {
      result.push(props);
    }
  });

  return result;
}


function updateOrInsertText(data) {
  if (typeof data === 'string') {
    data = JSON.parse(data);
  }

  const container = document.getElementById('container');
  let div = container.querySelector(`#${data.id}`);

  if (div) {
    // 更新已有组件
    div.innerText = data.text || '';
  } else {
    // 新建组件
    div = document.createElement('div');
    div.id = data.id;
    div.innerText = data.text || '';
    container.appendChild(div);
  }

  // 无论更新或新建，都重新应用样式
  const style = data.style || {};
  for (let key in style) {
    div.style[key] = style[key];
  }
  div.dataset.type = data.type;
  setActiveComponent(data.id);
}


function updateOrInsertImg(data) {
  if (typeof data === 'string') {
    data = JSON.parse(data);
  }

  const container = document.getElementById('container');
  let div = container.querySelector(`#${data.id}`);

  if (div) {
    // 更新已有组件
    const img = div.querySelector('img')
    img.src = data.img
  } else {
    // 新建组件
    div = document.createElement('div');
    div.id = data.id;
    const img = document.createElement('img');
    img.src = data.img;
    div.appendChild(img);
    container.appendChild(div);
  }

  // 无论更新或新建，都重新应用样式
  const style = data.style || {};
  for (let key in style) {
    div.style[key] = style[key];
  }
  div.dataset.type = data.type;
  setActiveComponent(data.id);
}

function downloadHTML() {
  resetAllStatus();// 清除选中状态
  return document.documentElement.outerHTML;
}


function capture() {
  resetAllStatus();// 清除选中状态
  html2canvas(container, {
    scale: getScale(),
    useCORS: true,
  }).then(canvas => {
    const targetWidth = parseFloat(container.style.width || '0');
    const targetHeight = parseFloat(container.style.height || '0');

    const croppedCanvas = document.createElement('canvas');
    croppedCanvas.width = targetWidth;
    croppedCanvas.height = targetHeight;

    const ctx = croppedCanvas.getContext('2d');
    ctx.drawImage(canvas, 0, 0, targetWidth + maxoffest, targetHeight + maxoffest, 0, 0, targetWidth, targetHeight);

    captureHandler.postMessage(croppedCanvas.toDataURL("image/png"));
  });
}



